import UserAuth from '@/api/UserAuth'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号码输入有误'))
      } else {
        if (this.ruleForm.userName !== '') {
          this.$refs.ruleForm.validateField('passWord')
        }
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.ruleForm.passWord) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        // 1==验证码登录 2=密码登录
        loginType: 2,
        userName: '',
        passWord: '',
        capCode: '',
        mobile: process.env.NODE_ENV === 'development' ? '17629003319' : '',
        smsCode: process.env.NODE_ENV === 'development' ? '111111' : ''
      },
      rules: {
        userName: [
          {
            validator: validateUsername,
            trigger: 'blur'
          }
        ],
        passWord: [
          {
            validator: validatePassword,
            trigger: 'blur'
          }
        ],
        capCode: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入验证码'))
              } else {
                callback()
              }
            }
          }
        ],
        mobile: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                callback(new Error('请输入手机号'))
              } else if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error('手机号格式有误'))
              } else {
                callback()
              }
            }
          }
        ],
        smsCode: [
          {
            required: true,
            message: '请输入验证码'
          }
        ]
      },
      // 用户秘密登录按钮控制
      disabled: false,
      logintext: '登录',
      // 验证码路径
      captchaImage: UserAuth.captchaImage(),
      // 发送等待时间间隔
      times: 60,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async(isValid) => {
        let intv
        // 表单验证
        if (isValid) {
          try {
            this.disabled = true
            intv = setInterval(function() {
              this.logintext = this.logintext === '登录......' ? '登录' : this.logintext += '...'
            }.bind(this), 600)
            // 发起登录请求
            const isLoginOk = await this.$store.dispatch('doLogin', this.ruleForm)
            if (isLoginOk) {
              // 获取菜单
              const isMenuOk = await this.$store.dispatch('fetchMenu')
              if (isMenuOk) {
                this.$notify({
                  type: 'success',
                  title: '成功',
                  message: '登录成功',
                  duration: 1000
                })
                // 拉取通用接口
                await this.$store.dispatch('fetchRegin')
                // 重定向到通用的 home 界面
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              }
            }
          } catch (e) {
            this.refreshVlidCode()
          }
          finally {
            clearInterval(intv)
            this.logintext = '登录'
            this.disabled = false
          }
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }, // 刷新验证码
    refreshVlidCode() {
      this.captchaImage = UserAuth.captchaImage()
    }, // 切换登录方式
    toggleLogin() {
      this.ruleForm.loginType = this.ruleForm.loginType === 1 ? 2 : 1
    },
    // 发送短信验证码
    sendSmsCode(formName) {
      const mobile = this.ruleForm.mobile
      this.$refs[formName].validateField('mobile', async(phoneError) => {
        let n = -1
        try {
          if (!phoneError) {
            this.times--
            n = setInterval(() => {
              this.times--
              if (this.times < 0) {
                clearInterval(n)
                this.times = 60
              }
            }, 1000)
            const { msg } = await UserAuth.sendMsg(mobile)
            this.$notify({
              type: 'success',
              title: '成功',
              message: msg,
              duration: 1000
            })
          }
        } catch (e) {
          clearInterval(n)
          this.times = 60
        }
      })
    }
  },
  computed: {
    getSendDisabled() {
      return this.times < 60
    },
    getSendText() {
      return this.times === 60 ? '获取验证码' : `剩余${this.times}秒`
    }
  },
  created() {
  }
}
